package com.ybu.service.impl;

import com.ybu.common.Constants;
import com.ybu.common.MD5Utils;
import com.ybu.common.ServiceCode;
import com.ybu.common.ServiceException;
import com.ybu.mapper.UserMapper;
import com.ybu.pojo.dto.RegisterDTO;
import com.ybu.pojo.dto.UserLoginDTO;
import com.ybu.pojo.entity.User;
import com.ybu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @ProjectName: cmall-ybu
 * @Titile: UserServiceImpl
 * @Author: Lucky
 * @Description: 用户业务实现类
 */
@Service //业务层
@Slf4j
public class UserServiceImpl implements UserService {
    //注入持久层
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(RegisterDTO registerDTO) {
        //判断密码与重复密码是否一致
        if(!registerDTO.getPassword().equals(registerDTO.getRePassword())){
           throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"两次输入的密码不一致");
        }
        //生成salt
        String salt = UUID.randomUUID().toString().replace("-","");
        // 对密码进行加密
        String password = MD5Utils.enctype(registerDTO.getPassword(), salt, Constants.HASH_TIME);
        log.debug("密码加密后：{}",password);
        log.debug("salt：{}",salt);
        //封装user
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        //使用加密后的密码
        user.setPassword(password);
        user.setSalt(salt);
        user.setIsDelete(Constants.IS_NOT_DELETE);
        user.setCreatedUser(registerDTO.getUsername());
        //调用持久层进行新增用户
        int result = userMapper.insert(user);
        if(result != 1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"注册用户失败");
        }
    }

    @Override
    public void login(UserLoginDTO userLoginDTO) {
        //根据用户名去查询用户
        User user = userMapper.getByName(userLoginDTO.getUsername());
        if (user == null || user.getUsername() == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"登录用户名不能为空");
        }
        //判断是否被锁定
        if (user.getIsDelete() == 1){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"该账户被锁定");
        }
        //判断密码
        //将登录密码进行加密
        String password = MD5Utils.enctype(userLoginDTO.getPassword(),user.getSalt(),Constants.HASH_TIME);
        if (!password.equals(user.getPassword())){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"密码错误");
        }
        //用户登录成功，保证逻辑的粒度
    }


}
